<template>
  <div class="content-section">
    <el-card class="upload-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>我的上传</span>
        </div>
      </template>

      <div class="report-list">
        <div
          v-for="item in reportList"
          :key="item.code"
          class="report-card"
        >
          <div class="report-info">
            <div class="img-wrapper">
              <img
                crossOrigin="anonymous"
                :src="item.coverPic"
                alt="Document"
                class="document-image"
              />
              <div class="img-title">{{ item.title }}</div>
            </div>
            <div class="report-details">
              <div class="title-section">
                <el-icon><Tickets /></el-icon>
                <el-tooltip :content="item.title" placement="top" effect="dark">
                  <span @click="viewReport(item)" class="report-title-link">
                    {{ item.title }}
                  </span>
                </el-tooltip>
              </div>
              <div class="meta-info">
                <div class="meta-item">
                  <el-icon><EditPen /></el-icon>
                  <span>{{ item.author }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Timer /></el-icon>
                  <span>{{ formatDate(item.publishTime) }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Tickets /></el-icon>
                  <span>共{{ item.sizeNum }}页</span>
                </div>
                <div class="meta-item">
                  <el-tag :type="item.price === '免费' ? 'primary' : 'warning'">
                    {{ item.price === "免费" ? "免费" : `¥${item.price}` }}
                  </el-tag>
                </div>
              </div>
              <div class="upload-time">
                <span>{{ uploadTimeLabel }}</span>
                <span class="label">{{ formatDate(item.publishTime) }}</span>
              </div>
            </div>
          </div>

          <div class="action-panel">
            <!-- 审核状态 -->
            <el-tag :type="statusTypeMap[item.myStatus]">
              {{ item.myStatusTxt }}
            </el-tag>

            <!-- 上/下架 -->
            <el-button
              :icon="Top"
              link
              class="action-btn"
              :disabled="loading || item.myStatus !== '1'"
              @click="toggleShow(item)"
            >
              {{ getShowText(item) }}
            </el-button>

            <!-- 编辑 -->
            <el-button
              :icon="Edit"
              link
              class="action-btn"
              @click="editReport(item)"
            >
              {{ editText }}
            </el-button>

            <!-- 删除 -->
            <el-button
              :icon="Delete"
              link
              class="action-btn"
              :loading="
                actionLoading[item.code] && actionType[item.code] === 'delete'
              "
              @click="confirmDelete(item)"
            >
              {{ deleteText }}
            </el-button>
          </div>
        </div>
        <el-empty
          v-if="!loading && reportList.length === 0"
          :description="loading ? '数据加载中...' : '当前暂无上传数据'"
          :image-size="120"
        />
      </div>

      <Pagination
        :total="Number(props.total)"
        :page="currentPage"
        :limit="pageSize"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </el-card>

    <el-dialog v-model="dialogVisible" width="900px">
      <div class="dialog-body">
        <el-form :model="form" label-width="120px" class="report-form">
          <!-- 上传 PDF -->
          <el-form-item label="上传报告">
            <el-upload
              ref="uploadRef"
              class="upload-demo"
              :action="''"
              :auto-upload="false"
              accept=".pdf"
              :file-list="fileList"
              :before-upload="beforeUpload"
              @change="handleFileChange"
              list-type="text"
            >
              <template #trigger>
                <el-button type="primary">选择PDF文件</el-button>
                <span>(若不修改报告本身 则留空)</span>
              </template>
            </el-upload>
          </el-form-item>

          <!-- 标题 -->
          <el-form-item label="编辑标题">
            <el-input v-model="form.title" placeholder="请输入报告标题" />
          </el-form-item>

          <!-- 描述 -->
          <el-form-item label="描述内容">
            <el-input
              v-model="form.script"
              type="textarea"
              placeholder="描述"
            />
          </el-form-item>

          <!-- 机构名称 -->
          <el-form-item label="机构名称">
            <el-input v-model="form.org" placeholder="请输入机构名称" />
          </el-form-item>

          <!-- 作者 -->
          <el-form-item label="作者姓名">
            <el-input v-model="form.author" placeholder="请输入作者姓名" />
          </el-form-item>

          <!-- 报告价格 -->
          <el-form-item label="报告价格">
            <el-input
              v-model="form.price"
              placeholder="请输入报告价格"
              style="width: 250px"
            />
          </el-form-item>

          <!-- 发布日期 -->
          <el-form-item label="发布日期">
            <el-date-picker
              v-model="form.publishTime"
              type="date"
              placeholder="请选择发布日期"
              format="YYYYMMDD"
              value-format="YYYYMMDD"
              style="width: 250px"
            />
          </el-form-item>

          <!-- 报告行业 -->
          <el-form-item label="报告行业">
            <el-cascader
              v-model="form.industry"
              :options="industryOptionsList"
              placeholder="请选择行业"
              clearable
              style="width: 250px"
            />
          </el-form-item>

          <!-- 选择封面 -->
          <el-form-item label="选择封面">
            <div class="cover-grid">
              <div
                v-for="cover in coverList"
                :key="cover.code"
                class="cover-item"
                :class="{ selected: form.coverPic === cover.code }"
                @click="form.coverPic = cover.code"
              >
                <img :src="cover.label" alt="封面" />
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div class="button-group">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确认修改</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import dayjs from 'dayjs'
import { upload } from '../../api/upload'
import { Edit, Delete, Top } from '@element-plus/icons-vue'
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const props = defineProps({
  uploadsdata: { type: Array, required: true },
  loading: { type: Boolean, default: false },
  total: { type: Number, default: 0 },
  initialPage: { type: Number, default: 1 },
  initialSize: { type: Number, default: 10 },
})
const emit = defineEmits(['refresh'])
const form = reactive({
  report: null, title: '', script: '', org: '', author: '',
  publishTime: '', price: '', industry: [], coverPic: '', code: ''
})
const reportList = ref(props.uploadsdata)
// 添加数据监听
watch(() => props.uploadsdata, (newVal) => {
  reportList.value = newVal
})

const actionLoading = reactive({})
const actionType = reactive({})
// 分页
const currentPage = ref(props.initialPage)
const pageSize = ref(props.initialSize)
watch(() => props.initialPage, v => currentPage.value = v)
watch(() => props.initialSize, v => pageSize.value = v)


watch(() => props.uploadsdata, v => reportList.value = v)


const handleCurrentChange = (page) => {
  currentPage.value = page
  emit('refresh', { pageNum: page, pageSize: pageSize.value })
}
const handleSizeChange = (limit) => {
  pageSize.value = limit
  currentPage.value = 1
  emit('refresh', { pageNum: 1, pageSize: limit })
}




const fileList = ref([])
const uploadRef = ref(null)
const coverList = ref([])
const industryOptionsList = ref([])

// 文字变量
const uploadTimeLabel = ref('上传时间：')
const editText = ref('修改报告')
const deleteText = ref('删除报告')

const dialogVisible = ref(false)
// myStatus 状态映射：0-审核中，1-已通过，2-未通过
const statusTypeMap = { '0': 'warning', '1': 'success', '2': 'danger' }
const formatDate = ts => dayjs.unix(Number(ts)).format('YYYY-MM-DD')


// 初次加载
//  const loadReports = async () => {
//   listLoading.value = true
//   try {
//     const res = await upload.myReportList()
//     reportList.value = res.data.myReportList.info || []
//   } catch {
//     ElMessage.error('列表加载失败')
//   } finally {
//     listLoading.value = false
//   }
// }

// 修改编辑
const editReport = async (item) => {
  // 1. 先加载封面和行业选项，确保 cascader 有数据
  await handleUpload()

  // 2. 存 code，用于后续提交
  form.code = item.code

  // 3. 调用详情接口
  const res = await upload.editReport({ code: item.code })
  const data = res.data.updateReport

  // 4. 填表
  form.title = data.title
  form.script = data.script || ''
  form.org = data.org
  form.author = data.author
  form.publishTime = dayjs.unix(data.publishTime).format('YYYYMMDD')
  form.price = data.price

  // —— 关键：根据后端返回的两个 ID 构造 cascader 值 —— 
  if (data.PM_industry_2_id && data.PM_industry_2_id !== '0') {
    form.industry = [data.PM_industry_1_id, data.PM_industry_2_id]
  } else {
    form.industry = [data.PM_industry_1_id]
  }

  form.coverPic = data.coverPic

  // 5. 清空或设置 PDF 预览
  fileList.value = []

  // 6. 打开弹窗
  dialogVisible.value = true
}


const submitEdit = async () => {


  if (!form.code) {

    return
  }

  const formData = new FormData()
  formData.append('report', form.report)
  Object.entries(form).forEach(([key, val]) => {
    if (key === 'report') return
    if (Array.isArray(val)) formData.append(key, val[val.length - 1])
    else formData.append(key, val)
  })
  const res = await upload.editReport(formData)

  if (res.code === 0) {
    ElMessage.success('修改成功')
    dialogVisible.value = false
  } else {
    ElMessage.error(res.msg)
  }
  emit('refresh')

}


// 文字显示函数
const getShowText = (item) => {
  // if (item.myStatus !== '1') return '审核中不可操作'
  return item.IS_show === '0' ? '上架' : '下架'
}

// 上/下架
const toggleShow = async (item) => {
  if (item.myStatus !== '1') return
  actionLoading[item.code] = true
  actionType[item.code] = 'toggle'
  try {
    const target = item.IS_show === '0' ? '1' : '0'
    const res = await upload.toggleShow({ code: item.code, IS_show: target })
    if (res.code === 0) {
      ElMessage.success(target === '1' ? '上架成功' : '下架成功')
      emit('refresh')
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch {
    ElMessage.error('操作出错')
  } finally {
    actionLoading[item.code] = false
    actionType[item.code] = ''
  }
}


// 删除确认 & 删除
const confirmDelete = (item) => {
  ElMessageBox.confirm('确认删除该报告？', '提示', {
    type: 'warning'
  }).then(async () => {
    actionLoading[item.code] = true
    actionType[item.code] = 'delete'
    try {
      const res = await upload.deleteReport({ code: item.code })
      if (res.code === 0) {
        ElMessage.success('删除成功')
        await emit('refresh')
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (err) {
      ElMessage.error('删除失败，请稍后重试')
    } finally {
      actionLoading[item.code] = false
      actionType[item.code] = null
    }
  }).catch(() => { })
}


const beforeUpload = (file) => {
  const isPdf = file.type === 'application/pdf'
  if (!isPdf) ElMessage.error('仅支持 PDF 格式')
  return isPdf
}

const handleFileChange = (_, lst) => {
  const pdfs = lst.filter(f => f.raw && f.raw.type === 'application/pdf')
  fileList.value = pdfs
  form.report = pdfs.length ? pdfs[0].raw : null
}

const removeFile = (file) => {
  const idx = fileList.value.indexOf(file)
  if (idx !== -1) fileList.value.splice(idx, 1)
  form.report = fileList.value.length ? fileList.value[0].raw : null
}



const handleUpload = async () => {
  const cov = await upload.getCover()
  coverList.value = Object.values(cov.data.coverPic)
  const ind = await upload.getIndustry()
  industryOptionsList.value = Object.values(ind.data.industry).map(item => ({
    value: item.code,
    label: item.label,
    children: item.children
      ? Object.values(item.children).map(c => ({ value: c.code, label: c.label }))
      : []
  }))
}

const viewReport = (item) => {
  // 1. 审核中不能查看
  if (item.myStatus === '0') {
    ElMessage.warning('该报告审核中，暂不可查看')
    return
  }
  // 2. 未上架不能查看
  if (item.IS_show === '0') {
    ElMessage.warning('该报告未上架，暂不可查看')
    return
  }
  if (item.price === '0') {
    // 解析免费报告详情页的完整URL
    const freeUrl = router.resolve({
      name: 'productDetail',
      params: { code: item.code }
    }).href;

    // 在新标签页打开免费报告
    window.open(freeUrl, '_blank');
  } else {
    // 解析付费报告详情页的完整URL
    const paidUrl = router.resolve({
      name: 'productDetailcharge',
      params: { code: item.code }
    }).href;

    // 在新标签页打开付费报告
    window.open(paidUrl, '_blank');
  }
}



onMounted(() => {
  // loadReports()
})
</script>

<style lang="scss" scoped>
.content-section {
  animation: fadeIn 0.3s ease;
}
.upload-card {
  height: 730px;
  margin: 0;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
}
.report-list {
  height: 578px;
  overflow-y: auto;
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 4px;
  }
}
.report-card {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.2s;
  &:hover {
    background-color: rgba(0, 128, 209, 0.05);
  }
  &:last-child {
    border-bottom: none;
  }
}
.report-info {
  display: flex;
  gap: 20px;
  flex: 1;
  min-width: 0;
}

.img-wrapper {
  position: relative;

  .img-title {
    position: absolute;
    top: 25%;
    left: 45%;
    /* 先把文字中心移到容器中心 */
    transform: translate(-50%, -50%) rotate(-5deg);
    /* 文字样式 */
    font-size: 7px;
    font-weight: bold;
    font-style: italic;
    color: #ffffff;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
    white-space: nowrap;
    pointer-events: none;
    text-align: center;
    width: 100px;
    white-space: nowrap; /* 防止文本换行 */
    overflow: hidden; /* 隐藏溢出的内容 */
    text-overflow: ellipsis; /* 显示省略号来代表被修剪的文本 */
  }
  .document-image {
    width: 120px;
    height: 175px;
    object-fit: cover;
  }
}
.report-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  gap: 8px;
  .title-section {
    display: flex;
    align-items: center;
    gap: 8px;
    .report-title {
      font-size: 16px;
      font-weight: 600;
      color: #151618;
      margin: 0;
    }
    .el-tag {
      font-size: 14px;
      padding: 4px 10px;
    }
  }
  .meta-info {
    display: flex;
    align-items: center;
    gap: 20px;
    color: rgba(21, 22, 24, 0.72);
    .meta-item {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 13px;
      .el-icon {
        font-size: 14px;
        color: rgba(21, 22, 24, 0.56);
      }
    }
  }
  .upload-time {
    font-size: 13px;
    color: rgba(21, 22, 24, 0.72);
    .label {
      margin-left: 4px;
    }
  }
}
.action-panel {
  display: flex;
  align-items: center;
  justify-content: space-around;
  gap: 25px;
  width: 40%;
  .action-btn {
    color: #0080d1;
    font-size: 14px;
    padding: 0;
  }
}
.icon-icon_pdf {
  color: #ff7861;
  font-size: 22px;
}

.cover-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 14px;
}

.cover-item {
  position: relative;
  border: 2px solid transparent;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  img {
    width: 100%;
    height: 120px;
    object-fit: cover;
  }
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
  }
  &.selected {
    border-color: #409eff;
    box-shadow: 0 8px 20px rgba(64, 158, 255, 0.3);
  }
}
.button-group {
  margin-top: 20px;
  text-align: center;
}
.report-title-link {
  display: inline-block;
  max-width: 320px; /* 根据你的布局调整宽度 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #409eff; /* 链接颜色，可按需调整 */
  cursor: pointer;
  text-decoration: none;
}
.report-title-link:hover {
  text-decoration: underline;
}
</style>
